#include "PShaderDX9.h"
#include "../Texture/Texture2DDX9.h"

CPShaderDX9::CPShaderDX9( mString a_sFileName )
: CPShader(a_sFileName)
{
    m_pShaderCode      = NULL;
    m_pShaderDebugInfo = NULL;
    m_pConstantTable   = NULL;
    m_pShader          = NULL;
}

CPShaderDX9::~CPShaderDX9( )
{
    SAFE_RELEASE(m_pShaderCode);
    SAFE_RELEASE(m_pShaderDebugInfo);
    SAFE_RELEASE(m_pConstantTable);
    SAFE_RELEASE(m_pShader);
}

mVoid CPShaderDX9::Compile( )
{
    D3DXCompileShaderFromFileA(m_sFileName.c_str(), NULL, &CID3D9Include::g_D3D9Include, "main", 
        "ps_3_0", D3DXSHADER_DEBUG, &m_pShaderCode, &m_pShaderDebugInfo, &m_pConstantTable);
    if (m_pShaderDebugInfo)
    {
        mChar* err = (mChar*)m_pShaderDebugInfo->GetBufferPointer();        
        (*g_pDebug) << "PShader compile error: \n" << err << "\n";
    }

    g_D3DDevice.pD3D9Device->CreatePixelShader((DWORD*)m_pShaderCode->GetBufferPointer(),
        &m_pShader);
}

mVoid CPShaderDX9::Bind( )
{
    g_D3DDevice.pD3D9Device->SetPixelShader(m_pShader);
}

mBool CPShaderDX9::SendConstantValue( const std::string &a_sConstName, mVoid *a_pValue, size_t a_ValueSize, TChangeFreq a_ChangeFreq )
{
    D3DXHANDLE hValue;
    hValue = m_pConstantTable->GetConstantByName(0, a_sConstName.c_str());
    m_pConstantTable->SetValue(g_D3DDevice.pD3D9Device, hValue, a_pValue, a_ValueSize);
    return true;
}

mBool CPShaderDX9::SendTexture( const std::string &a_sTextureName, CTexture2D *a_pTexture )
{
    CTexture2DDX9 *pTexDX9 = static_cast<CTexture2DDX9*>(a_pTexture);
    D3DXHANDLE hTexture = m_pConstantTable->GetConstantByName( 0, a_sTextureName.c_str() );
    if (hTexture == 0)
        return false;
    m_pConstantTable->GetSamplerIndex( hTexture );
    g_D3DDevice.pD3D9Device->SetTexture( m_pConstantTable->GetSamplerIndex( hTexture ), pTexDX9->Texture() );
    return true;
}